package cn.xiaohaoo.datacollection;

import cn.xiaohaoo.medicine.util.mongo.MongoDatabaseUtils;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Selectable;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Iterator;


/**
 * 数据集下载 http://www.sohu.com/a/252058287_661477
 */
public class MedicineImgPageProcessor implements PageProcessor {
    private static final Logger LOGGER = LoggerFactory.getLogger(MedicineImgPageProcessor.class);
    @Override
    public void process(Page page) {
        Iterator<Selectable> iterator = page.getHtml().xpath("//article/p").nodes().iterator();
        while (iterator.hasNext()) {
            Selectable next = iterator.next();
            if (next.xpath("img").get() != null) {
                String name = iterator.next().xpath("span/text()").get().split("：")[0];
                try {
                    //HttpUtil.downloadFile(next.xpath("img/@src").get(), new File("./datasets/dataset1/" + name +
                    //        ".jpg"));
                    Document document = new Document();
                    document.append("name", name);
                    document.append("img", next.xpath("img/@src").get());
                    MongoDatabaseUtils.insertDocument(MongoDatabaseUtils.MEDICINE_DETAIL_COLLECTION,document);
                } catch (Exception e) {
                    LOGGER.error("======>{}出错了！",name);
                }
            }
        }
    }

    @Override
    public Site getSite() {
        return new Site().setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like " +
                "Gecko) Chrome/79.0.3945.130 Safari/537.36");
    }

    public static void main(String[] args) {
        LocalDateTime begin = LocalDateTime.now();
        Spider.create(new MedicineImgPageProcessor()).addUrl("http://www.sohu.com/a/252058287_661477").thread(15).run();
        System.out.println("爬取用时：" + Duration.between(begin, LocalDateTime.now()).toMinutes() + "分钟");
    }
}
